package com.sunny.util.struts2;

import com.sunny.util.json.JsonUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.codehaus.jackson.map.ObjectMapper;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by tongchengke on 2016/8/25.
 * 用来输出数据到页面
 */
public class Struts2Utils {

    private static final String TEXT_CONTENT_TYPE = "text/plain";
    private static final String JSON_CONTENT_TYPE = "application/json";
    private static final String XML_CONTENT_TYPE = "application/xml";
    private static final String HTML_CONTENT_TYPE = "text/html";
    private static final String JS_CONTENT_TYPE = "text/javascript";
    private static final String EXCEL_CONTENT_TYPE = "application/vnd.ms-excel";

    private static final String HEADER_ENCODING = "encoding";
    private static final String HEADER_NOCACHE = "no-cache";
    private static final String DEFAULT_ENCODING = "UTF-8";
    private static final boolean DEFAULT_NOCACHE = true;

    /**
     *
     * @param text
     */
    public static void renderText(String text) {
        render(text,TEXT_CONTENT_TYPE);
    }

    /**
     *
     * @param json
     */
    public static void renderJson(String json) {
        render(json,JSON_CONTENT_TYPE);
    }

    /**
     *
     * @param obj
     */
    public static void renderJson(Object obj){
        HttpServletResponse response = initResponse(JSON_CONTENT_TYPE);
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.writeValue(response.getWriter(), obj);
        } catch (IOException e) {
            throw new IllegalArgumentException(e);
        }
    }

    public static void renderJsonp(String text,String callback) {
        StringBuffer sb = new StringBuffer();
        sb.append(callback);
        sb.append("(");
        sb.append(text);
        sb.append(")");
        render(sb.toString(),JS_CONTENT_TYPE);
    }

    public static void renderJsonp(Object obj,String callback){
        String json = JsonUtils.toJson(obj);
        renderJsonp(json,callback);
    }

    public static void renderXml(String xml) {
        render(xml,XML_CONTENT_TYPE);
    }

    public static void renderHtml(String html) {
        render(html, HTML_CONTENT_TYPE);
    }

    public static void render(String content, String contentType, String... headers) {
        HttpServletResponse response = initResponse(contentType, headers);
        try {
            response.getWriter().write(content);
            response.getWriter().flush();
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    /**
     * 设置 HttpServletResponse 信息
     *
     * @param contentType
     * @return 返回 HttpServletResponse对象
     */
    public static HttpServletResponse initResponse(String contentType, String... headers) {
        // 分析headers参数
        String encoding = DEFAULT_ENCODING;
        boolean noCache = DEFAULT_NOCACHE;
        for (String header : headers) {
            String headerName = StringUtils.substringBefore(header, ":");
            String headerValue = StringUtils.substringAfter(header, ":");

            if (StringUtils.equalsIgnoreCase(headerName, HEADER_ENCODING)) {
                encoding = headerValue;
            } else if (StringUtils.equalsIgnoreCase(headerName, HEADER_NOCACHE)) {
                noCache = Boolean.parseBoolean(headerValue);
            } else {
                throw new IllegalArgumentException(headerName + "不是一个合法的header类型");
            }
        }

        HttpServletResponse response = ServletActionContext.getResponse();

        // 设置headers参数
        String fullContentType = contentType + ";charset=" + encoding;
        response.setContentType(fullContentType);
        if (noCache) {
//            ServletUtils.setNoCacheHeader(response);
            setNoCacheHeader(response);
        }

        return response;
    }

    /**
     * 设置客户端无缓存Header.
     */
    public static void setNoCacheHeader(HttpServletResponse response) {
        // Http 1.0 header
        response.setDateHeader("Expires", 0);
        response.addHeader("Pragma", "no-cache");
        // Http 1.1 header
        response.setHeader("Cache-Control", "no-cache");
    }

}
